<?php
/**
 * Created by PhpStorm.
 * User: linyida
 * Date: 2019/7/26
 * Time: 下午2:51
 */
namespace App\Storage;

use EasySwoole\Component\Singleton;
use EasySwoole\MysqliPool\Mysql;

class ChatMessageMysql {

    use Singleton;
    protected $table = 'ven_chat_message_log';

    function __construct()
    {
    }

    /**
     * 存储一条消息
     * 格式: "{"fromUserFd":1,"action":WebSocketEvent::,"username":"username","avatar":"avatar","shopId":"shopId"}"
     * @param $message
     * @return bool
     */
    public function saveMessage($message) {
        $db = Mysql::getInstance()->pool('mysql')->getObj();
        $db->insert($this->table,$message);
        Mysql::getInstance()->pool('mysql')->recycleObj($db);
    }

    /**
     * 获取数据
     * @param $where ['k' => 'v'] 条件
     * @return array
     */
    public function readMessage($where) {
        $db = Mysql::getInstance()->pool('mysql')->getObj();
        $data = $db->get($this->table,$where);
        Mysql::getInstance()->pool('mysql')->recycleObj($db);

        if ($data) {
            return $data;
        }
        return [];
    }

    /**
     * 更新数据
     * @param $where
     * @param $data
     * @return mixed
     */
    public function updateMessage($where, $data) {
        $db = Mysql::getInstance()->pool('mysql')->getObj();
        $res = $db->where($where)->update($this->table, $data);
        Mysql::getInstance()->pool('mysql')->recycleObj($db);
        return $res;
    }

    /**
     * 获取历史消息
     * @param $shopId
     * @param $userId
     * @return mixed
     */
    public function getHistoryMessage($shopId,$userId) {
//        var_dump($shopId);
        $db = Mysql::getInstance()->pool('mysql')->getObj();
        if ($db) {
            $db ->where('shop_id',$shopId,'=','and')
                ->where('from_user_id',$userId,'=','and')
                ->where('to_user_id',$userId,'=','or');
            $data = $db->get($this->table);
            $sql = $db->getLastQuery();
            return $data;
        }
    }
}